package com.stars.easyms.base.trace;

import com.stars.easyms.base.trace.function.TraceExecutor;
import com.stars.easyms.base.util.TraceUtil;

/**
 * <p>className: EasyMsTraceHelper</p>
 * <p>description: EasyMsTrace帮助类</p>
 *
 * @author guoguifang
 * @version 1.7.1
 * @date 2020/12/19 3:53 下午
 */
public class EasyMsTraceHelper {

    public static Object setTraceIdIfNecessary(TraceExecutor traceExecutor) throws Throwable {
        // 获取当前traceId
        String traceId = EasyMsTraceSynchronizationManager.getTraceId();
        boolean isNewTrace = false;
        if (traceId == null) {
            traceId = TraceUtil.getTraceId();
            isNewTrace = true;
            EasyMsTraceSynchronizationManager.setTraceId(traceId);
        }

        try {
            return traceExecutor.execute(traceId);
        } finally {
            if (isNewTrace) {
                EasyMsTraceSynchronizationManager.clearTraceInfo();
            }
        }
    }

    private EasyMsTraceHelper() {
    }
}
